import Taro from '@tarojs/taro'

const BASE_URl = "http://npis.mocoder.cn/"
export const myRequest = (options) => {
  return new Promise((resolve, reject) => {
    Taro.request({
        url: BASE_URl + options.url,
        method: options.method || "POST",
        data: options.data || {},
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': Taro.getStorageSync('token')
        },
        success: async (res) => {
          if (res.statusCode !== 200) { //http状态码
            Taro.showToast({
              title: "数据加载失败",
              icon: "none"
            })
            return;
          } else {
            if (res.data.ret !== 200) {
              if (res.data.ret === 405) {
                let oldtoken = Taro.getStorageSync('token');
                let result1 = await this.$myRequest({
                  access_token: oldtoken,
                  url: `?s=App.Auth.RefreshAccessToken`
                }).then()
                {
                  Taro.setStorageSync('token', result.data.access_token);
                  let result2 = await this.$myRequest({
                    url: `?s=App.User_Student.UserProfile`
                  }).then()
                  {
                    Taro.setStorageSync('userInfo', result.data);
                  }
                }
              } else if (res.data.ret === 406) {
                setTimeout(function () {
                  Taro.navigateTo({
                    url: '/pages/login/login'
                  })
                }, 1500);
              }
              await Taro.showToast({
                title: res.data.msg,
                icon: "none"
              })
            }
          }
          resolve(res)
        }
        ,
        fail: (err) => {
          Taro.showToast({
            title: "加载失败",
            icon: "none"
          })
          reject(err)
        }
      }
    )
  })
}
